/**
 * webView功能扩展:
 * 1 启动时注入脚本
 * 2 webview输出到autojs控制台
 */

/**
 * 初始化
 * @param {*} webViewWidget webView控件
 * @param {*} jsFile   初始化js路径
 */
function init(webViewWidget, jsFile) {
    // 开启硬件加速
    webViewWidget.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null);
    webViewWidget.webViewClient = new JavaAdapter(android.webkit.WebViewClient, {
        onPageFinished: (webView, curUrl)=>{
            console.log('页面加载完成');
            ui.run(() => {
                jsFile.forEach((file, index) => {
                    try {
                        let js = files.read(file);
                        webViewWidget.loadUrl("javascript:" + js);
                        console.log("注入脚本: " + file);
                    } catch (e) {
                        toastLog("注入脚本失败: " + file);
                        console.error(e);
                    }
                });
            })
        },
        shouldOverrideUrlLoading: (webView, curUrl) => {
            let url = curUrl.a.a;
            try {
                if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://")) {
                    webView.loadUrl(url);
                } else {
                    importPackage(android.net);
                    let uri = Uri.parse(url);
                    app.startActivity(new Intent(Intent.ACTION_VIEW).setData(uri).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
                }
                // 返回true代表自定义处理，返回false代表触发webview加载
                return true;
            } catch(e) {
                console.error(e);
                console.error('无法打开' + url);
                toast('无法打开' + url);
            }
        },
        shouldInterceptRequest: (webView, req) => {
            let url = req.a.a;
            if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://")) {
            } else {
                console.log('拦截到' + JSON.stringify(url));
            }
        }
    });
    // webViewWidget.setWebContentsDebuggingEnabled(true);
    webViewWidget.webChromeClient = new JavaAdapter(android.webkit.WebChromeClient, {
        onConsoleMessage: (msg) => {
            console.log("[%s:%s]: %s", msg.sourceId(), msg.lineNumber(), msg.message());
        }
    });
}

/**
 * 渲染markdown文件
 * @param {*} webViewWidget webView控件
 * @param {*} markdownFile  markdown文件
 */
function showMarkdown(webViewWidget, markdownFile) {
    let markdownLib = files.cwd() + "/res/js/marked.min.js";
    let markdownStr = files.read(markdownFile, encoding = "utf-8");
    markdownStr = markdownStr.replace("\r", "\n\n");
    let unencodedHtml = new java.lang.String(
    "<!doctype html>\t\r" +
    "<html>\t\r" +
    "<head>\t\r" +
    "<meta charset='utf-8'/>\t\r" +
    "</head>\t\r" +
    "<body>\t\r" +
    "<div id='content'></div>\t\r" +
    "<script src='https://cdn.jsdelivr.net/npm/marked/marked.min.js'></script> \t\r" +
    // "<script src='file://" + markdownLib + "'></script> \t\r" +
    "<script>\t\r" +
    "    document.getElementById('content').innerHTML =\t\r" +
    "    marked(`" + markdownStr + "`,{breaks: true});\t\r" +
    "</script> \t\r" +
    "</body>\t\r" +
    "</html>");
    let encodedHtml = java.util.Base64.getEncoder().encodeToString(unencodedHtml.getBytes());
    ui.webView.loadData(encodedHtml, "text/html", "base64");
}

module.exports = {
    init: init,
    showMarkdown: showMarkdown
}